package com.bangdao.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author chen
 * @create 2021-01-03
 */

/**
 * 多线程之间按顺序调用，实现A->B->C。三个线程启动，要求如下：
 *  AA打印5次，BB打印10次，CC打印15次
 *  接着
 *  AA打印5次，BB打印10次，CC打印15次
 *  。。。打印10轮
 *
 * 分析实现方式： *
 * 1. 有一个锁Lock，3把钥匙Condition
 * 2. 有顺序通知（切换线程），需要有标识位
 * 3. 判断标志位
 * 4. 输出线程名 + 内容
 * 5. 修改标识符，通知下一个
 */
public class ThreadOrderAccessDemo {
    public static void main(String[] args) {
        ShareDataThree dataThree = new ShareDataThree();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                dataThree.println5A();
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                dataThree.println10B();
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                dataThree.println15C();
            }
        },"C").start();
    }
}

class ShareDataThree {
    // 线程标识位，通过它区分线程切换
    private Integer flag = 1;
    private ReentrantLock lock = new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();

    public void println5A() {
        lock.lock();
        try {
            //判断
            while (flag != 1) {
                condition1.await();
            }
            //干活
            System.out.println(Thread.currentThread().getName() + ": AAAAA");
            //通知
            flag = 2;
            condition2.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void println10B() {
        lock.lock();
        try {
            //判断
            while (flag != 2) {
                condition2.await();
            }
            //干活
            System.out.println(Thread.currentThread().getName() + ": BBBBBBBBBB");
            //通知
            flag = 3;
            condition3.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void println15C() {
        lock.lock();
        try {
            //判断
            while (flag != 3) {
                condition3.await();
            }
            //干活
            System.out.println(Thread.currentThread().getName() + ": CCCCCCCCCCCCCCC");
            //通知
            flag = 1;
            condition1.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}